﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Kawanon.Usability;
using Kawanon.Usability.Visualization;
using Microsoft.Win32;
using System.Diagnostics;
using QTPlugin;
using System.Reflection;
using Kawanon.Sessions;
using Kawanon.BandExtension;

namespace Kawanon.QtHoney
{
	public partial class OptionsForm : Form
	{
		private static Dictionary<Type, string[]> s_informations = new Dictionary<Type, string[]>();

		static OptionsForm()
		{
			s_informations.Add(typeof(GestureInformation), new string[] {
				"Gesture.Enabled",
				"Gesture.DrawTrails",
			});
			s_informations.Add(typeof(SessionManagerInformation), new string[] {
			});
		}

		private IPluginServer m_server;

		public OptionsForm(IPluginServer server)
		{
			InitializeComponent();

			m_server = server;
		}

		private void toolStripButton_Rendering_Click(object sender, EventArgs e)
		{
			Utility.EditInformation<RenderingInformation>(this, "描画の設定", Resource.RenderingInformation);
		}

		private void toolStripButton_Expressions_Click(object sender, EventArgs e)
		{
			GestureForm form = new GestureForm(m_server);
			form.ShowDialog(this);
		}

		//private void toolStripTextBox_MinimumDistance_Validating(object sender, CancelEventArgs e)
		//{
		//    ToolStripTextBox edit = (ToolStripTextBox)sender;
		//    //if (!Array.TrueForAll(edit.Text.ToCharArray(), c => Char.IsDigit(c)))
		//    //{
		//    //}
		//    edit.Tag = null;

		//    try
		//    {
		//        uint val = UInt32.Parse(edit.Text);

		//        if (val > 0)
		//        {
		//            edit.Tag = val;
		//            return;
		//        }
		//    }
		//    catch (FormatException)
		//    {
		//    }

		//    System.Media.SystemSounds.Beep.Play();
		//    e.Cancel = true;

		//    edit.SelectAll();
		//}

		private ListViewItem FindItemByTag(ListView.ListViewItemCollection c, object tag)
		{
			foreach (ListViewItem item in c)
			{
				if (tag.Equals(item.Tag))
				{
					return item;
				}
			}
			return null;
		}

		private void SyncCheck(string key, object info, bool storing)
		{
			ListViewItem item = FindItemByTag(listView1.Items, key);
			if (item == null)
			{
				return;
			}

			string[] tokens = key.Split('.');
			PropertyInfo prop = info.GetType().GetProperty(tokens[tokens.Length - 1]);
			if (storing)
			{
				prop.SetValue(info, item.Checked, null);
			}
			else
			{
				bool b = (bool)prop.GetValue(info, null);
				item.Checked = b;
			}
		}

		private void SyncInformation(object info, bool storing)
		{
			Type t = info.GetType();
			string[] keys = s_informations[t];
			foreach (string key in keys)
			{
				SyncCheck(key, info, storing);
			}
		}

		private void SyncCheck(string key, bool storing)
		{
			RegistryKey reg = Plugins.OpenRegistryKey(storing);
			if (reg != null)
			{
				ListViewItem item = FindItemByTag(listView1.Items, key);
				if (storing)
				{
					reg.SetValue(key, item.Checked, RegistryValueKind.DWord);
				}
				else
				{
					item.Checked = Convert.ToBoolean(reg.GetValue(key));
				}
				reg.Close();
			}
		}

		private void OptionsForm_Load(object sender, EventArgs e)
		{
			//RegistryKey key = Plugins.OpenRegistryKey(false);
			//if (key == null)
			//{
			//    return;
			//}

			//ListViewItem[] items = new ListViewItem[listView1.Items.Count];
			//listView1.Items.CopyTo(items, 0);
			//string[] names = Array.ConvertAll(items, item => (string)item.Tag);
			//foreach (ListViewItem item in listView1.Items)
			//{
			//    string name = (string)item.Tag;
			//    item.Checked = Convert.ToBoolean(key.GetValue(name, item.Checked));
			//}

			GestureInformation info = Persistence.GetInformation<GestureInformation>();
			SyncInformation(info, false);

			SyncCheck("DebugMode", false);

			//toolStripTextBox_MinimumDistance.Text = info.MinimumDistance.ToString();
		}

		private void OptionsForm_FormClosed(object sender, FormClosedEventArgs e)
		{
			ValidateChildren();

			GestureInformation info = Persistence.GetInformation<GestureInformation>();
			SyncInformation(info, true);

			//foreach (ListViewItem item in listView1.Items)
			//{
			//    string name = (string)item.Tag;
			//    key.SetValue(name, item.Checked, RegistryValueKind.DWord);
			//}

			SyncCheck("DebugMode", true);

			//if (toolStripTextBox_MinimumDistance.Tag != null)
			//{
			//    info.MinimumDistance = (uint)toolStripTextBox_MinimumDistance.Tag;
			//}

			Persistence.SaveInformation(info);
		}

		private void toolStripButton_Export_Click(object sender, EventArgs e)
		{
			SaveFileDialog dlg = new SaveFileDialog();
			dlg.Title = "設定のエクスポート";
			dlg.FileName = "QTHoney.reg";
			dlg.Filter = "レジストリ設定 (*.reg)|*.reg";

			DialogResult res = dlg.ShowDialog(this);
			if (res == DialogResult.Cancel)
			{
				return;
			}

			RegistryKey key = Plugins.OpenRegistryKey(false);

			ProcessStartInfo si = new ProcessStartInfo();
			si.FileName = "regedit";
			si.Arguments = String.Format("/e \"{0}\" \"{1}\"", dlg.FileName, key.ToString());

			try
			{
				Process proc = Process.Start(si);
				proc.WaitForExit();
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		private void toolStripButton_About_Click(object sender, EventArgs e)
		{
			AboutForm form = new AboutForm();
			form.ShowDialog();
		}

		private void toolStripButton_AddressBar_Click(object sender, EventArgs e)
		{
			Utility.EditInformation<AddressBarInformation>(this, "アドレスバーの設定", null);
		}

		private void toolStripButton_Gesture_Click(object sender, EventArgs e)
		{
			Utility.EditInformation<GestureInformation>(this, "マウスジェスチャの詳細設定", null);
		}

	}
}
